package com.idreems.constellations;

import java.util.HashMap;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

import com.flurry.android.FlurryAgent;
import com.idreems.model.JsonItem;

public class FullWebPageActivity extends Activity implements OnClickListener, OnKeyListener
{
	// 设定WebViewClient的处理程序
	class MyWebViewClient extends WebViewClient
	{
		@Override
		public void doUpdateVisitedHistory(WebView view, String url, boolean isReload)
		{
			back.setEnabled(webView.canGoBack());
			forward.setEnabled(webView.canGoForward());
		}

		@Override
		public void onPageFinished(WebView view, String url)
		{
			// 设置程序的标题为网页的标题
			if (webView.getTitle() != null)
			{
				FullWebPageActivity.this.setTitle(webView.getTitle());
			}
			findViewById(R.id.OriginalProgress).setVisibility(View.GONE);
			/* This call inject JavaScript into the page which just finished loading. */
			view.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon)
		{
			FullWebPageActivity.this.setTitle(R.string.webview_loading_url);
			back.setEnabled(webView.canGoBack());
			forward.setEnabled(webView.canGoForward());
			findViewById(R.id.OriginalProgress).setVisibility(View.VISIBLE);
		}

		@Override
		public boolean shouldOverrideUrlLoading(final WebView webView, final String url)
		{
			webView.loadUrl(url);
			return false;
		}
	}

	Button back;
	Button forward;
	Button first;
	Button last;
	Button share;
	EditText url;
	WebView webView;
	String htmlString;
	String webUrl = "";

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.full_webpage);
		Bundle bundle = getIntent().getExtras();
		webUrl = "";
		if (bundle != null)
		{
			webUrl = getIntent().getExtras().getString(JsonItem.WEBURL);
		}

		/* An instance of this class will be registered as a JavaScript interface */
		class MyJavaScriptInterface
		{
			@JavascriptInterface
			public void processHTML(String html)
			{
				// process the html as needed by the app
				htmlString = html;
			}
		}

		// 建立显示画面上Button,EditText,WebView类的实例变量
		first = (Button) findViewById(R.id.Button01);
		back = (Button) findViewById(R.id.Button02);
		forward = (Button) findViewById(R.id.Button03);
		last = (Button) findViewById(R.id.Button04);
		share = (Button) findViewById(R.id.Button05);
		url = (EditText) findViewById(R.id.EditText01);
		webView = (WebView) findViewById(R.id.WebView01);
		webView.setWebViewClient(new MyWebViewClient());
		webView.setFocusable(false);
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		/* Register a new JavaScript interface called HTMLOUT */
		webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
		final WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setSupportZoom(true);
		settings.setBuiltInZoomControls(true);

		// 设定Button和EditText的监听功能
		back.setOnClickListener(this);
		forward.setOnClickListener(this);
		first.setOnClickListener(this);
		last.setOnClickListener(this);
		share.setOnClickListener(this);
		url.setOnKeyListener(this);
		if (!TextUtils.isEmpty(webUrl))
		{
			url.setVisibility(View.GONE);
			webView.loadUrl(webUrl);
		}
	}

	// 按下Button时的处理程序
	public void onClick(View v)
	{
		if (v == back)
		{
			if (webView.canGoBack())
			{
				webView.goBack();
			}
		}
		else if (v == forward)
		{
			if (webView.canGoForward())
			{
				webView.goForward();
			}
		}
		else if (v == first)
		{
			if (webView.canGoBackOrForward(-2))
			{
				webView.goBackOrForward(-2);
			}
		}
		else if (v == last)
		{
			if (webView.canGoBackOrForward(+2))
			{
				webView.goBackOrForward(+2);
			}
		}
		else if (v == share)
		{
			HashMap<String, String> mapsHashMap = new HashMap<String, String>();
			mapsHashMap.put("share", webUrl);
			FlurryAgent.logEvent("share", mapsHashMap);
			// webView.clearHistory();
//			shareHtml(this, htmlString);
			sendHtmlContentTo(this,webView.getTitle(),webUrl,htmlString);
		}
	}

	public static void shareHtml(Context context, String htmlString)
	{
		Intent sharingIntent = new Intent(Intent.ACTION_SEND);
		sharingIntent.setType("text/html");
		sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(htmlString));
		context.startActivity(Intent.createChooser(sharingIntent, "Share using"));
	}

	public static void sendHtmlContentTo(final Context context, String title, String url,String htmlString)
	{
		//FIXME:此部分发送的格式有问题，待修复
		final Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/html");
		intent.putExtra(Intent.EXTRA_SUBJECT, title);
		final HtmlCleaner cleaner = new HtmlCleaner();
		final TagNode[] bodyNode = cleaner.clean(htmlString).getElementsByName("body", true);
		if (bodyNode.length > 0) {
            intent.putExtra(
                    Intent.EXTRA_TEXT,
                    Html.fromHtml("<p><strong>"
                            + title
                            + "</strong></p><p>Published on <a href='"
                            + url
                            + "'>"
                            + title
                            + "</a></p><p>"
                            + cleaner.getInnerHtml(bodyNode[0])
                            + "</p><p>("
                            + context.getString(R.string.TxtViaEasyRSS)
                            + " | <a href='https://market.android.com/details?id=com.idreems.constellations'>每日更新，最新的星座运程!</a>)</p>"));
            context.startActivity(Intent.createChooser(intent, context.getString(R.string.TxtSendTo)));
        }
	}

	// 於url(EditText)编辑框按下ENTER時的处理程序，下载新的网页
	public boolean onKey(View v, int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_ENTER)
		{
			webView.loadUrl(url.getText().toString());
			return true;
		}
		return false;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack())
		{
			webView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		if (webView != null)
		{
			webView.stopLoading();
		}
	}
}
